package connectfour;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.servlet.http.*;

import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;

public class QuitGameServlet extends HttpServlet{
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		//MemcacheService mc = MemcacheServiceFactory.getMemcacheService();
		
		Game game = null;
		
		/*
		// get the game entity corresponding to this game 
		if(mc.contains("game" + req.getParameter("gID"))){
			game = (Game) mc.get("game" + req.getParameter("gID"));
		}
		else{
			Query query = pm.newQuery(Game.class);
			query.declareImports("import com.google.appengine.api.datastore.Key");
			query.setFilter("key == keyParam");
			query.setUnique(true);
			query.declareParameters("Key keyParam");
		
			try {
				Game result = (Game) query.execute(KeyFactory.createKey("Game", 
						Long.parseLong(req.getParameter("gID"))));
				game = result;
	
			} finally {
				query.closeAll();
	
			}
		}
		*/
		Query query = pm.newQuery(Game.class);
		query.declareImports("import com.google.appengine.api.datastore.Key");
		query.setFilter("key == keyParam");
		query.setUnique(true);
		query.declareParameters("Key keyParam");
	
		try {
			Game result = (Game) query.execute(KeyFactory.createKey("Game", 
					Long.parseLong(req.getParameter("gID"))));
			game = result;

		} finally {
			query.closeAll();

		}
		
		Player p1 = null;
		Player p2 = null;		
		/*
		// get the player entity coressponding to p1
		if(mc.contains("player" + game.getUserHost().getUserId())){
			p1 = (Player) mc.get("player" + game.getUserHost().getUserId());
		}
		else{
			p1 = pm.getObjectById(Player.class, game.getHost());
		}
		*/
		p1 = pm.getObjectById(Player.class, game.getHost());
		
		// set p1's status to 0 (not in a game) and set the game to being done
		//p1.setStatus(0);
		game.isOver(true);
		
		/*
		// if there was a p2 in the game that is being ended, get its entity and update that as well
		if(game.getOpponent() != null){
			if(mc.contains("player" + game.getUserOpponent().getUserId())){
				p2 = (Player) mc.get("player" + game.getUserHost().getUserId());
			}
			else{
				p2 = pm.getObjectById(Player.class, game.getOpponent());
			}
			//p2.setStatus(0);
		}
		 */
		p2 = pm.getObjectById(Player.class, game.getOpponent());
		
		Transaction tx = pm.currentTransaction();
		Queue q = QueueFactory.getDefaultQueue();
		
		try{
			tx.begin();
			
			pm.makePersistent(game);
			
			TaskOptions t = TaskOptions.Builder.url("/persist").param("pKey", 
					KeyFactory.keyToString(p1.getKey())).param("status", "0").param("wins", "0")
					.param("losses", "0").param("ratio", "0");
			q.add(t);
			
			if(p2 != null){
				t = TaskOptions.Builder.url("/persist").param("pKey", 
						KeyFactory.keyToString(p2.getKey())).param("status", "0").param("wins", "0")
						.param("losses", "0").param("ratio", "0");
				q.add(t);
			}
			
			/*
			pm.makePersistent(p1);
			if(p2 != null){
				pm.makePersistent(p2);
			}
			*/
			
			
			tx.commit();
			
		} finally {
			if(tx.isActive()){
				tx.rollback();
			}
			pm.close();
		}
		
		/*
		// update the memcache
		mc.put("game" + game.getKey().getId(), game);
		mc.put("player" + p1.getPlayer().getUserId(), p1);
		if(p2 != null){
			mc.put("player" + p2.getPlayer().getUserId(), p2);
		}
		*/
		resp.sendRedirect("/lobby.jsp");
	}
}
